﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using sqlserverextensions.Helper;


    public partial class UserDefinedFunctions
    {
        /// <summary>
        /// Funktion zur Ermittelung der Prüfziffer.
        /// z.B. 19052-0 die 0 wird von der Funktion zurückgegeben
        /// </summary>
        /// <param name="valueWithoutCheckDigit">Zahl für die die Prüfziffer ermittelt werden soll</param>
        /// <returns>1-stellige Prüfziffer</returns>
        [Microsoft.SqlServer.Server.SqlFunction]
        public static SqlString RailCheckDigit(SqlString valueWithoutCheckDigit)
        {
            Int16 errSeverity = 16;

            SqlInt64 digitSum = 0;
            string singleChar = String.Empty;

            if (valueWithoutCheckDigit.IsNull)
                return null;

            try
            {
                for (int i = 0; i <= valueWithoutCheckDigit.Value.Length - 1; i++)
                {
                    singleChar = valueWithoutCheckDigit.Value.Substring(i, 1);

                    if (i % 2 == 0)
                        digitSum += RailDigitSum(SqlInt16.Parse(singleChar) * 2);
                    else
                        digitSum += RailDigitSum(SqlInt16.Parse(singleChar) * 1);

                }


            }
            catch (Exception ex)
            {
                ExceptionHelper.EvaluateException(ex, errSeverity);
                return null;
            }


            if (digitSum % 10 != 0)
                return (10 - (digitSum % 10)).ToSqlString();
            else
                return "0";
        }
    };

